<template>
  <div class="app-container">
    <div class="flex items-center justify-between mb-4">
      <el-button size="default" type="primary" @click="handleCreated">创建群聊</el-button>
      <div class="flex items-center">
        <el-button size="default" type="primary" @click="handleSearch">查 询</el-button>
        <el-button plain size="default" @click="handleReset">重 置</el-button>
      </div>
    </div>
    <div class="flex flex-wrap">
      <div class="flex items-center marginRB10">
        <span class="w-20 text-right">群主ID：</span>
        <el-input v-model="listQuery.user_id" clearable placeholder="请输入群主ID" style="width:220px;"></el-input>
      </div>
      <div class="flex items-center marginRB10">
        <span class="w-32 text-right">群聊类型：</span>
        <el-select v-model="listQuery.category_id" clearable filterable placeholder="请选择" style="width:220px;"
                   value-key="">
          <el-option v-for="item in options2"
                     :key="item.value"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>

      </div>
      <div class="flex items-center marginRB10">
        <span class="w-20 text-right">群号：</span>
        <el-input v-model="listQuery.code" clearable placeholder="请输入群号" style="width:220px;"></el-input>
      </div>
      <div class="flex items-center marginRB10">
        <span class="w-32 text-right">创建时间：</span>
        <el-date-picker
          v-model="date_value"
          class="mr-5"
          clearable
          end-placeholder="邀请结束时间"
          range-separator="-"
          start-placeholder="邀请开始时间"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          @change="handleChangeDate"
        >
        </el-date-picker>
      </div>
      <div class="flex items-center marginRB10">
        <span class="w-32 text-right">群聊名称：</span>
        <el-input v-model="listQuery.name" clearable placeholder="请输入群聊名称" style="width:220px;"></el-input>
      </div>
      <div class="flex items-center marginRB10">
        <span class="w-32 text-right">群聊规模：</span>
        <el-select v-model="listQuery.allow_member_count" clearable filterable placeholder="请选择" style="width:220px;"
                   value-key="">
          <el-option v-for="item in options"
                     :key="item.value"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div class="flex items-center marginRB10">
        <span class="w-32 text-right">群主昵称：</span>
        <el-input v-model="listQuery.nickname" clearable placeholder="请输入群主昵称" style="width:220px;"></el-input>
      </div>
    </div>

    <el-table :data="tableData" border stripe @selection-change="handleSelectionChange">
      <el-table-column v-for="col in columns"
                       :key="col.id"
                       :label="col.label"
                       :prop="col.property"
                       :sortable="col.property === 'created_format' || col.property === 'members'"
                       :width="col.width"
                       @selection-change="handleSelectionChange">
        <template slot-scope="scope">
					<!-- <span v-if="col.property === 'category_name'">
						<span v-if="scope.row[col.property] === 1">同城</span>
						<span v-if="scope.row[col.property] === 2">交友</span>
						<span v-if="scope.row[col.property] === 3">娱乐</span>
					</span> -->
          <span v-if="['head_picture','avatar'].includes(col.property)">
						<img :src="scope.row[col.property]" alt="">
					</span>
          <span v-else>{{ scope.row[col.property] }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="全选"
        type="selection"
        width="155">
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot="header" slot-scope="scope">
          <span style="padding-right: 10px;">操作</span>
          <el-button :disabled="multipleSelection.length > 0 ? false : true" size="default" type="danger"
                     @click="handleAllDissolve">全部解散
          </el-button>
        </template>
        <template slot-scope="scope">
          <el-button size="small" type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" style="color: #f56c6c;" type="text" @click="handleDissolve(scope.row)">解散</el-button>
        </template>
      </el-table-column>
    </el-table>
    <cus-pagination v-show="total>0" :limit.sync="listQuery.perPage" :page.sync="listQuery.page" :total="total"
                    @pagination="getList"/>

    <!-- 创建群聊 -->
    <el-dialog
      :visible.sync="dialogVisible"
      title="创建群聊"
      width="30%"
      @close="handleCloseDialog">

      <el-form ref="dataForm" :inline="false" :model="form" :rules="rules" label-width="120px" size="normal">
        <el-form-item label="群主ID" prop="user_id">
          <el-input v-model="form.user_id" placeholder="请输入群主ID"></el-input>
        </el-form-item>
        <el-form-item label="群聊类型" prop="category_id">
          <el-select v-model="form.category_id" class="w-full" clearable filterable placeholder="请选择" value-key="">
            <el-option v-for="item in options2"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="群聊规模" prop="allow_member_count">
          <el-select v-model="form.allow_member_count" class="w-full" clearable filterable placeholder="请选择"
                     value-key="">
            <el-option v-for="item in options"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="handleConfirm('dataForm')">确定</el-button>
			</span>
    </el-dialog>
    <!-- 创建群聊成功 -->
    <el-dialog
      :visible.sync="successVisible"
      center
      title="创建成功"
      width="30%"
      @close="handleCloseDialog">
      <div class="flex justify-items-center py-4">
        <span class="w-24 text-right ">群号：</span>
        <span>{{ successInfo.code }}</span>
        <span class="p-0 ml-4 text-blue-500" @click="copyContent">复制</span>
      </div>
      <div class="flex py-4">
        <span class="w-24 text-right">群主ID：</span>
        <span>{{ successInfo.user_code }}</span>
      </div>
      <div class="flex py-4">
        <span class="w-24 text-right">群主昵称：</span>
        <span>{{ successInfo.nickname }}</span>
      </div>
      <span slot="footer">
				<el-button type="primary" @click="successVisible = false">确定</el-button>
			</span>
    </el-dialog>

    <!-- 编辑 -->
    <el-dialog
      :visible.sync="editDialogVisible"
      title="编辑"
      width="30%"
      @close="handleCloseDialog">
      <el-form ref="editForm" :inline="false" :model="editForm" :rules="rules" label-width="80px" size="normal">
        <el-form-item label="群聊头像" prop="avatar">
          <div class="avatarBox">
            <div class="block">
              <el-avatar :size="100" :src="editForm.avatar" icon="el-icon-user-solid"></el-avatar>
            </div>
            <el-upload
              :before-upload="beforeAvatarUpload"
              :http-request="customizeUpload"
              :on-success="handleAvatarSuccess"
              :show-file-list="false"
              action="#"
              class="avatar-uploader avatar">
              <span class="block align-middle">修改头像</span>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="群聊名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入群聊名称"></el-input>
        </el-form-item>
        <el-form-item label="群聊规模" size="allow_member_count">
          <el-select v-model="editForm.allow_member_count" clearable filterable placeholder="请选择" style="width:220px;">
            <el-option v-for="item in options"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>

      <span slot="footer">
				<el-button @click="editDialogVisible = false">返回</el-button>
				<el-button type="primary" @click="handleModification('editForm')">修改</el-button>
			</span>
    </el-dialog>

    <!-- 单独解散 -->
    <el-dialog
      :visible.sync="separateDissolutionVisible"
      title="解散群聊"
      width="30%"
      @close="handleCloseDialog">
      <el-form ref="separateDissolution" :inline="false" :model="separateDissolutionInfo" label-width="80px"
               size="normal">
        <el-form-item class="inline-block" label="群聊头像" style="width: 45%">
          <el-image :src="separateDissolutionInfo.avatar" class="rounded-full w-24 h-24" fit="fill"></el-image>
        </el-form-item>
        <el-form-item class="inline-block" label="群主头像" style="width: 45%">
          <el-image :src="separateDissolutionInfo.head_picture" class="rounded-full w-24 h-24" fit="fill"></el-image>
        </el-form-item>
        <el-form-item class="inline-block" label="群聊名称" style="width: 45%">
          <el-input v-model="separateDissolutionInfo.name" disabled></el-input>
        </el-form-item>
        <el-form-item class="inline-block" label="群主昵称" style="width: 45%">
          <el-input v-model="separateDissolutionInfo.nickname" disabled></el-input>
        </el-form-item>
        <el-form-item class="inline-block" label="群聊类型" style="width: 45%">
          <span v-if="separateDissolutionInfo.category_name === 1">同城</span>
          <span v-if="separateDissolutionInfo.category_name === 2">交友</span>
          <span v-if="separateDissolutionInfo.category_name === 3">娱乐</span>
          <span v-else>暂无</span>
        </el-form-item>
        <el-form-item class="inline-block" label="群主ID" style="width: 45%">
          <el-input v-model="separateDissolutionInfo.user_code" disabled></el-input>
        </el-form-item>
        <el-form-item class="inline-block" label="群号" style="width: 45%">
          <el-input v-model="separateDissolutionInfo.code" disabled></el-input>
        </el-form-item>
        <el-form-item class="inline-block" label="群成员数" style="width: 45%">
          <el-input v-model="separateDissolutionInfo.members" disabled></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer">
				<el-button @click="separateDissolutionVisible = false">取 消</el-button>
				<el-button type="danger" @click="confirmSeparateDissolution">确定解散</el-button>
			</span>
    </el-dialog>

    <!-- 多个解散 -->
    <el-dialog
      :visible.sync="multipleDissolutionVisible"
      title="解散群聊"
      width="30%"
      @close="handleCloseDialog">
      <div class="mb-4">共选择 <span class="text-red-600">{{ multipleSelection.length }}</span> 个群聊</div>
      <div class="flex">
        <div class="flex flex-1">
          <span>群号：</span>
          <div>
            <p v-for="item of multipleSelection" class="mb-2" :key="item.id">{{ item.code }}</p>
          </div>
        </div>
        <div class="flex flex-1">
          <span>群主ID：</span>
          <div>
            <p v-for="item of multipleSelection" class="mb-2" :key="item.id">{{ item.user_code }}</p>
          </div>
        </div>
        <div class="flex flex-1">
          <span>群主昵称：</span>
          <div>
            <p v-for="item of multipleSelection" class="mb-2" :key="item.id">{{ item.nickname }}</p>
          </div>
        </div>
      </div>
      <span slot="footer">
				<el-button @click="multipleDissolutionVisible = false">取消</el-button>
				<el-button type="danger" @click="handleAllDissolution">全部解散</el-button>
			</span>
    </el-dialog>


  </div>
</template>

<script>
import {ChatListAdd, ChatListDismiss, ChatListEdit, getGroupChatList} from "@/api/groupChat/groupChatList";

export default {
  name: 'groupChatList',
  data() {
    return {
      multipleDissolutionVisible: false,
      multipleSelection: [],
      separateDissolutionVisible: false,
      separateDissolutionInfo: {},
      editDialogVisible: false,
      successVisible: false,
      dialogVisible: false,
      editForm: {
        avatar: '', //require('../../assets/img/logoGH.png'),
        name: '',
        allow_member_count: null
      },
      form: {
        user_id: '',
        category_id: '',
        allow_member_count: ''
      },
      rules: {
        name: [{required: true, message: '请输入群聊名称', trigger: 'blur'}],
        user_id: [{required: true, message: '请输入群主ID', trigger: 'blur'}],
        category_id: [{required: true, message: '请选择群聊类型', trigger: 'change'}],
        allow_member_count: [{required: true, message: '请选择群聊规模', trigger: 'change'}],
      },
      date_value: '',
      total: 0,
      listQuery: {
        page: 1,
        perPage: 10,
        start_time: '',
        end_time: "",
        user_id: '',
        category_id: '',
        allow_member_count: '',
        code: '',
        name: '',
        nickname: '',
        column: '',
        direction: ''
      },
      options: [
        {
          value: 100,
          label: '100人'
        },
        {
          value: 200,
          label: '200人'
        },
        {
          value: 300,
          label: '300人'
        },
        {
          value: 500,
          label: '500人'
        },
      ],
      options2: [
        {
          value: 1,
          label: '同城'
        },
        {
          value: 2,
          label: '交友'
        },
        {
          value: 3,
          label: '娱乐'
        },
      ],
      tableData: [],
      columns: [
        {
          id: 1,
          label: '群头像',
          property: 'avatar',
          width: 'auto'
        },
        {
          id: 2,
          label: '群聊名称',
          property: 'name',
          width: 'auto'
        },
        {
          id: 3,
          label: '群聊类型',
          property: 'category_name',
          width: 'auto'
        },
        {
          id: 4,
          label: '群号',
          property: 'code',
          width: 'auto'
        },
        {
          id: 5,
          label: '群主头像',
          property: 'head_picture',
          width: 'auto'
        },
        {
          id: 6,
          label: '群主昵称',
          property: 'nickname',
          width: 'auto'
        },
        {
          id: 7,
          label: '群主ID',
          property: 'user_code',
          width: 'auto'
        },
        {
          id: 8,
          label: '群成员数',
          property: 'members',
          width: 'auto'
        },
        {
          id: 9,
          label: '创建时间',
          property: 'created_format',
          width: 'auto'
        }
      ],
      successInfo: {
        code: '',
        user_code: '',
        nickname: ''
      },
      row_id: ''
    }
  },
  created() {
    this.getList()
  },
  mounted() {

  },
  methods: {
    handleChangeDate(value) {
      if (value) {
        this.listQuery.start_time = value[0]
        this.listQuery.end_time = value[1]
      } else {
        this.listQuery.start_time = undefined
        this.listQuery.end_time = undefined
      }
    },
    getList() {
      this.listLoading = true
      for (let key in this.listQuery) {
        this.listQuery[key] = this.listQuery[key] === '' ? undefined : this.listQuery[key]
      }
      getGroupChatList(this.listQuery).then(({data}) => {
        this.tableData = data.list
        this.total = data.meta.total
        this.listLoading = false
      })
    },
    handleSelectionChange(rows) {
      this.multipleSelection = rows
    },
    handleEdit(row) {
      this.row_id = row.id
      row.allow_member_count = 100
      // if (row.avatar) {
      //   this.editForm.avatar = row.avatar
      // }
      this.editForm =JSON.parse(JSON.stringify(row))
      this.editDialogVisible = true
    },
    handleModification(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          ChatListEdit(this.row_id, this.editForm).then(({code, data}) => {
            if (code === 200) {
              this.getList()
              this.successInfo = {
                code: data.code,
                user_code: data.user_code,
                nickname: data.nickname
              }
              this.$message({
                type: 'success',
                message: '修改成功'
              })
              this.editDialogVisible = false
            } else {
              return false
            }
          })
        } else {
          return false
        }
      })
    },
    handleDissolve(row) {
      this.separateDissolutionInfo = row
      this.separateDissolutionVisible = true
    },
    confirmSeparateDissolution() {
      let ids = this.separateDissolutionInfo.id
      ChatListDismiss(ids).then(res => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '解散成功'
          })
          this.getList()
          this.separateDissolutionVisible = false
        } else {
          return false
        }
      })
    },
    handleAllDissolve() {
      this.multipleDissolutionVisible = true
    },
    handleAllDissolution() {
      let ids = this.multipleSelection.map(item => item.id).toString();
      ChatListDismiss(ids).then(res => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '解散成功'
          })
          this.getList()
          this.multipleDissolutionVisible = false
        } else {
          return false
        }
      })
    },
    handleCreated() {
      this.dialogVisible = true
    },
    handleSearch() {
      this.listQuery.page = 1
      this.getList()
    },
    handleReset() {
      this.listQuery = {
        page: 1,
        perPage: 10,
        start_time: '',
        end_time: "",
        user_id: '',
        category_id: '',
        allow_member_count: '',
        code: '',
        name: '',
        nickname: '',
        column: '',
        direction: ''
      }
      this.date_value = ''
      this.getList()
    },
    handleConfirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          ChatListAdd(this.form).then(({code, data}) => {
            if (code === 200) {
              this.getList()
              console.log(data)
              this.successInfo = {
                code: data.code,
                user_code: data.user_code,
                nickname: data.nickname
              }
              this.$message({
                type: 'success',
                message: '创建成功'
              })
              this.successVisible = true

              this.dialogVisible = false
            } else {
              return false
            }
          })
        } else {
          return false
        }
      })
    },
    handleCloseDialog() {
      if (this.$refs['dataForm']) {
        this.$refs['dataForm'].clearValidate() // 清除整个表单的校验
        this.$refs['dataForm'].resetFields()
      }
      if (this.$refs['editForm']) {
        this.$refs['editForm'].clearValidate() // 清除整个表单的校验
        this.$refs['dataForm'].resetFields()

      }

    },
    copyContent() {
      let link = '群号：' + this.successInfo.code
      let copyInput = document.createElement('input')
      document.body.appendChild(copyInput)
      copyInput.setAttribute('value', link)
      copyInput.select()
      document.execCommand('copy')
      this.$notify({
        type: 'success',
        message: '复制成功',
        position: 'top-right',
        showClose: false,
        duration: 3000
      })
      copyInput.remove()
      this.successvisible = false
    },
    handleAvatarSuccess(res, file) {
      this.editForm.avatar = this.ossLastImgUrl
    },
    beforeAvatarUpload(file) {
      const isJPG = ['image/jpeg', 'image/png'].includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      return isLt2M
    },
  },
}
</script>

<style lang="scss" scoped>
.avatarBox {
  position : relative;

  .uploadImg {
    border-radius : 100%;
    overflow      : hidden;
  }

  .avatar {
    position : absolute;
    display  : none;

    span {
      display    : block;
      text-align : center;
    }
  }
}

.avatarBox:hover {
  .avatar {
    position      : absolute;
    top           : 0;
    left          : 0;
    border-radius : 100%;
    overflow      : hidden;
    display       : block;
    background    : rgba($color : #ffffff, $alpha : .45);
    z-index       : 10;
    color         : #000000;
  }
}

.block{
  width: 100px;
  height: 100px;
  line-height: 100px;
}
/deep/ .el-table__header .el-table-column--selection .cell .el-checkbox:before {
  content      : "全选";
  margin-right : 5px;
}

/deep/ .el-select {
  width : 100% !important;
}
</style>
